// app.js
const express = require("express");
const multer = require('multer');
const axios =require('axios');
const app = express();
const port = 3000;

app.use(express.json()); // 解析 JSON 格式的请求体
app.use(express.urlencoded({ extended: true })); // 解析 URL-encoded 格式的请求体


app.use((req, res, next) => {
  console.log("Time:", Date.now());
  next();
})
// 定义路由,路由中间件
app.get("/", (req, res) => {
  res.send("Hello, Express!");
});

app.get("/api/users", (req, res) => {
  const users =[{name: "Alice"}, {name: "Bob"}]
  res.send(users);
});
const upload = multer({ dest: 'uploads/' });
// 处理单个文件上传
app.post('/upload', upload.single('file'), (req, res) => {
  if (req.fileError) {
    return res.status(400).send(req.fileError);
  }
  const file = req.file;
  if (!file) {
    return res.status(400).send('No file uploaded');
  }
  res.send('File uploaded successfully');
});
// 处理 POST 请求
app.post('/api/submit', (req, res) => {
  const data = req.body;
  console.log('Received data:', data);
  res.statusCode=305;
  res.send('POST request received');
});
// --跨域配置
// app.use((req, res, next) => {
//   res.header('Access-Control-Allow-Origin', '*');
//   res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
//   next();
// });

// --jsonp解决跨域问题
app.get('/api/jsonp', (req, res) => {
  const callback = req.query.callback||"callback";
  const data = { message: 'Hello, JSONP!' };
  const jsonp = `${callback}(${JSON.stringify(data)})`;
  res.send(jsonp);
})
app.use('/api/hero',async( req, res) => {
  const resp=await  axios.get('https://pvp.qq.com/web201605/js/herolist.json');
  res.header('Access-Control-Allow-Origin', '*');
  res.send(resp.data);
})

// 异常中间件:回调函数包含了4个参数
// 注意事项:
// 1. 与异常中间件全局只包含一个
// 2、异常中间件可以传递给普通中间件
// 3，异常中间件需要放在所有中间件的最后
// 4、 异常中间件只能捕获回调函数中的异常

// --全局异常处理
process.on("uncaughtException", (err) => {
  console.log("uncaughtException:", err);
})

// --全局未捕获的Promise异常
process.on("unhandledRejection", (err) => {
  console.log("unhandledRejection:", err);
})


// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
